(function(module){
	module.login={
		loginForm: {},
		loadCaptcha: function(){
			$.post("/login/genericsImageCaptcha?time="+new Date().getTime(), "{}", function(data){
				module.login.loginForm.captchaKey=data.key;
				$("#captchaImg").attr("src","data:image/jpg;base64,"+data.base64Value);
			},'json')
		},
		loginRule: {
			account: [{required:true, message:"账号不能为空"}],
			password: [{required:true, message:"密码不能为空"}],
			validateCode: [{required:true, message:"验证码不能为空"}]
		},
		submit: function(){
			if(!$.valiForm("login", module.login.loginRule)){
				return false;
			}
			var login=$.formToData("login");
			login.password=md5(login.password);
			$.ajax({
				type: "post",
				url: '/login/loging',
				data:JSON.stringify(login),
				headers:{
					captchaKey: module.login.loginForm.captchaKey
				},
				success: function(data){
					console.log(data);
					var expire=data.tokenExpire-(new Date().getTime());
					$.cookie("tF", data.token, expire);
					$.cookie("tH", data.tokenHeader, expire);
					$.cookie("tT", expire);
					if(!$.cookie("tK")){
						$.cookie("tK", data.tokenKey);
					}
					var url=$.parseHrefParam('url')
					if(url){
						window.location.href=url;
					}else{
						window.location.href='/pages/admin/index.html';
					}
				},
				error:function(){
					module.login.loadCaptcha();
					return true;
				},
				dataType:"json"
			});
		},
		keyboardSubmit: function(input, event){
			event=event||window.event;
			if(event.keyCode==13){
				if(!input.value){
					return false;
				}else{
					var form=$("#login");
					var name=input.name;
					var inputs=form.find("input"), item;
					var next=false;
					for(var i=0, length=inputs.length; i<length; i++){
						item=inputs.eq(i);
						if(item.attr('name')==name){
							if(next){
								module.login.submit();
								break;
							}
							next=true;
							if(i>=length-1){
								i=-1;
							}
							continue;
						}
						if(next){
							if(!item.val()){
								item.focus();
								break;
							}
						}
						if(i>=length-1){
							i=-1;
						}
					}
					return false;
				}
			}
		}
	}
})($.module);